<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>素材管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-radio-group v-model="collect" class="action-head" @change="onCollectChange">
        <div class="tab-radio">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </div>
        <div class="upload-image">
          <el-button type="primary" @click="dialogUploadVisible = true">点击上传<i class="el-icon-upload el-icon--right"></i></el-button>
        </div>
      </el-radio-group>
      <!-- 素材列表 -->
      <el-row :gutter="10" v-loading="loading">
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          v-for="(img, index) in images"
          :key="index"
        >
          <el-card class="image-card">
            <el-image
              class="el-image"
              :src="img.url"
              fit="cover"
              lazy
            >
            </el-image>
            <div class="cover-image">
              <div class="bottom clearfix">
                <el-button type="warning" :icon="img.is_collected ? 'el-icon-star-on' : 'el-icon-star-off' " circle @click="onCollect(img.id, img.is_collected = !img.is_collected)"></el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="onDeleteImage(img.id)"></el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalCount"
        :page-size="per_page"
        :current-page.sync="page"
        @current-change="onCurrentPage"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="上传素材"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
    >
      <!--
        upload 组件本身就支持请求提交上传操作，说白了你使用它不用自己去发请求，它会自己发。
        请求方法：默认就是 POST
        请求路径：action，必须写完整路径
        请求头：headers
       -->
      <el-upload
        class="upload-demo"
        drag
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        :headers="uploadHeaders"
        name="image"
        multiple
        :show-file-list="false"
        :on-success="onUploadSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
// 导入素材相关api接口
import { getImages, collectImage, deleteImage } from '@/api/image'
export default {
  name: 'appImage',
  data () {
    const user = JSON.parse(window.localStorage.getItem('User'))
    return {
      // 加载状态
      loading: true,
      // 素材图片列表
      images: [],
      // 全部素材
      collect: false,
      // 总页码
      totalCount: null,
      // 一页显示多少
      per_page: 8,
      // 当前页
      page: 1,
      // 上传请求头
      uploadHeaders: {
        Authorization: `Bearer ${user.token}`
      },
      dialogUploadVisible: false
    }
  },
  methods: {
    // 获取素材图片列表
    async imagesLists (page = 1) {
      const res = await getImages({
        // 当前页
        page: this.page,
        // per_page每页显示10条数据
        per_page: this.per_page,
        // collect:false,获取全部素材图片,collect:true获取收藏素材图片
        collect: this.collect
      })
      try {
        const { results, total_count: totalCount } = res.data.data
        this.images = results
        this.totalCount = totalCount
        // 获取数据后关闭loading状态
        this.loading = false
      } catch (err) {
        return Promise.reject(err)
      }
    },
    // 全部&收藏切换
    onCollectChange () {
      this.imagesLists(this.page = 1)
    },
    // 分页点击事件
    onCurrentPage (page) {
      // 将当前点击的分页页码,传给getImages接口
      this.imagesLists()
    },
    // 收藏素材
    async onCollect (collectId, isCollect) { // onCollect (collectId-素材id, isCollect-是否收藏(true | false))
      await collectImage(collectId, {
        collect: isCollect
      })
      if (isCollect) {
        // 收藏提示
        this.$message({
          type: 'success',
          message: '已收藏'
        })
      }
    },
    // 删除素材
    onDeleteImage (collectId) {
      this.$confirm('您确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 调用删除素材接口
        await deleteImage(collectId)
        // 删除提示
        this.$message({
          type: 'success',
          message: '已删除'
        })
        // 重新获取图片素材列表
        this.imagesLists()
      })
    },
    // 上传
    onUploadSuccess () {
      // 关闭对话框
      this.dialogUploadVisible = false

      // 更新素材列表
      this.imagesLists(this.page)

      this.$message({
        type: 'success',
        message: '上传成功'
      })
    }
  },
  created () {
    // 执行获取素材图片列表方法,默认渲染全部并且渲染第一页数据
    this.imagesLists(this.page)
  }
}
</script>
<style lang="less">
.image-container{
  .box-card{
    .action-head{
      padding-bottom: 20px;
      display: flex;
      justify-content: space-between;
    }
    .el-row{
      margin-bottom: 20px;
      .el-col{
        .image-card{
          padding: 0;
          margin-bottom: 20px;
          position: relative;
          .el-image{
            width: 100%;
            height: 200px;
          }
          .cover-image{
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            position: absolute;
            transition: all .6s;
            &:hover{
              background: rgba(0, 0, 0, .4);
            }
            .bottom{
              display: none;
              position: absolute;
              top: 0;
              left: 30px;
            }
          }
          .cover-image:hover .bottom{
            display: block;
            top: 30px;
          }
        }
      }
    }
  }
}
</style>
